import { TreeItem, ExtensionContext, TreeDataProvider, EventEmitter, Event, window, Range, ViewColumn } from 'vscode'
import { FeedbackItem } from '../items/FeedbackItem'
import { CurrentFile } from '~/core/CurrentFile'
import { Log } from '~/utils/Log'
import { BaseTreeItem } from '../items/Base'

// 自定义树项类，用于展示中文字符
export class ChineseCharacterItem extends BaseTreeItem {
  constructor(
    ctx: ExtensionContext,
    public readonly text: string,
    public readonly line: number,
  ) {
    super(ctx)
    this.label = `Line ${line}:${text}`
    this.tooltip = `中文字符: ${text}\n行号: ${line}`
    this.iconPath = this.getIcon('string')
    
    // 添加点击跳转到对应行的命令
    // 只有当当前文件存在时才设置命令
    if (CurrentFile._currentUri) {
      this.command = {
        title: '跳转到行',
        command: 'vscode.open',
        arguments: [
          CurrentFile._currentUri,
          {
            selection: new Range(line - 1, 0, line - 1, 0),
            viewColumn: ViewColumn.Active
          }
        ]
      }
    }
  }
  
  // 定义上下文值，用于支持编辑和翻译操作
  // @ts-expect-error
  get contextValue(): string {
    return 'chinese-character-item-editable-translatable'
  }
  
  // 为了支持命令操作，添加所需的属性
  get keypath(): string {
    // 使用中文字符作为临时键名，实际应用中可能需要更好的命名策略
    return `${this.text}`
  }
  
  get locale(): string {
    // 返回默认语言
    return 'zh-CN'
  }
}

export class ReplaceProvider implements TreeDataProvider<BaseTreeItem> {
  private _onDidChangeTreeData: EventEmitter<BaseTreeItem | undefined> = new EventEmitter<BaseTreeItem | undefined>()
  readonly onDidChangeTreeData: Event<BaseTreeItem | undefined> = this._onDidChangeTreeData.event

  constructor(
    private ctx: ExtensionContext,
  ) {
    // 监听当前文件变化
    CurrentFile.onInitialized(() => this.refresh())
    CurrentFile.onHardStringDetected(() => this.refresh())
  }

  refresh(): void {
    this._onDidChangeTreeData.fire(undefined)
  }

  getTreeItem(element: BaseTreeItem): TreeItem {
    return element
  }

  async getChildren(element?: BaseTreeItem): Promise<BaseTreeItem[]> {
    if (element) {
      return []
    }

    // 获取当前文件内容
    const currentUri = CurrentFile._currentUri
    if (!currentUri) {
      return [new FeedbackItem(this.ctx, {
        text: '没有打开的文件',
        icon: 'info',
      })]
    }

    try {
      // 读取文件内容
      const document = await window.showTextDocument(currentUri)
      const text = document.document.getText()

      // 检测中文字符
      const chineseCharacters = this.detectChineseCharacters(text)

      if (chineseCharacters.length === 0) {
        return [new FeedbackItem(this.ctx, {
          text: '当前文件中未检测到中文字符',
          icon: 'check',
        })]
      }

      // 创建树项
      return chineseCharacters.map(item => new ChineseCharacterItem(
        this.ctx,
        item.text,
        item.line
      ))
    } catch (error) {
      Log.error('读取文件内容失败')
      return [new FeedbackItem(this.ctx, {
        text: '读取文件内容失败',
        icon: 'error',
        desc: String(error),
      })]
    }
  }

  // 过滤代码中的注释（包括HTML注释）
  private removeCommentsFromLine(line: string): string {
    // 处理单行注释
    const singleLineCommentIndex = line.indexOf('//')
    if (singleLineCommentIndex !== -1) {
      line = line.substring(0, singleLineCommentIndex)
    }
    
    // 处理同一行内的多行注释
    const multiLineCommentStart = line.indexOf('/*')
    const multiLineCommentEnd = line.indexOf('*/', multiLineCommentStart)
    if (multiLineCommentStart !== -1 && multiLineCommentEnd !== -1) {
      line = line.substring(0, multiLineCommentStart) + line.substring(multiLineCommentEnd + 2)
      // 递归检查是否还有其他注释
      return this.removeCommentsFromLine(line)
    }
    
    // 处理HTML注释 <!-- -->
    const htmlCommentStart = line.indexOf('<!--')
    const htmlCommentEnd = line.indexOf('-->', htmlCommentStart)
    if (htmlCommentStart !== -1 && htmlCommentEnd !== -1) {
      line = line.substring(0, htmlCommentStart) + line.substring(htmlCommentEnd + 3)
      // 递归检查是否还有其他注释
      return this.removeCommentsFromLine(line)
    }
    
    return line
  }

  // 检测中文字符（忽略注释中的字符，包括HTML注释）
  private detectChineseCharacters(text: string): { text: string; line: number }[] {
    const results: { text: string; line: number }[] = []
    const lines = text.split('\n')

    // 匹配中文字符的正则表达式
    const chineseRegex = /[一-龥]+/g
    
    // 多行注释状态跟踪
    let inMultiLineComment = false
    let inHtmlMultiLineComment = false

    for (let i = 0; i < lines.length; i++) {
      let line = lines[i]
      
      // 处理普通多行注释
      if (inMultiLineComment) {
        const commentEndIndex = line.indexOf('*/')
        if (commentEndIndex !== -1) {
          // 移除多行注释的剩余部分
          line = line.substring(commentEndIndex + 2)
          inMultiLineComment = false
        } else {
          // 整行都是多行注释的一部分，跳过
          continue
        }
      }

      // 处理HTML多行注释
      if (inHtmlMultiLineComment) {
        const htmlCommentEndIndex = line.indexOf('-->', 0)
        if (htmlCommentEndIndex !== -1) {
          // 移除HTML多行注释的剩余部分
          line = line.substring(htmlCommentEndIndex + 3)
          inHtmlMultiLineComment = false
        } else {
          // 整行都是HTML多行注释的一部分，跳过
          continue
        }
      }
      
      // 检查是否有新的普通多行注释开始
      const commentStartIndex = line.indexOf('/*')
      const commentEndIndex = line.indexOf('*/', commentStartIndex)
      
      if (commentStartIndex !== -1) {
        if (commentEndIndex !== -1) {
          // 多行注释在同一行内结束
          line = line.substring(0, commentStartIndex) + line.substring(commentEndIndex + 2)
        } else {
          // 多行注释跨越多行
          line = line.substring(0, commentStartIndex)
          inMultiLineComment = true
        }
      }
      
      // 检查是否有新的HTML多行注释开始
      const htmlCommentStartIndex = line.indexOf('<!--')
      const htmlCommentEndIndex = line.indexOf('-->', htmlCommentStartIndex)
      
      if (htmlCommentStartIndex !== -1) {
        if (htmlCommentEndIndex !== -1) {
          // HTML注释在同一行内结束
          line = line.substring(0, htmlCommentStartIndex) + line.substring(htmlCommentEndIndex + 3)
        } else {
          // HTML注释跨越多行
          line = line.substring(0, htmlCommentStartIndex)
          inHtmlMultiLineComment = true
        }
      }
      
      // 移除单行注释
      line = this.removeCommentsFromLine(line)
      
      // 检测中文字符
      let match
      while ((match = chineseRegex.exec(line)) !== null) {
        results.push({
          text: match[0],
          line: i + 1 // 行号从1开始
        })
      }
    }

    return results
  }
}
